package com.yuan.ocr.demo;

import com.yuan.util.string.CharUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @author YouYuan
 * @version 1.0
 * @date 2018/10/29 15:52
 */
public class TesseractOcrDemo {

    public static void main(String[] args) throws Exception {
        String path = "D:\\Temp\\Develop\\Img\\VerifyTest\\tmp-new";
        File root = new File(path);
        File[] files = root.listFiles(File::isFile);
        double succRateTess4j = 0;
        double afterSuccRateTess4j = 0;
        int realTotal = files.length;
        int afterTotalTess4j = realTotal;
        System.out.println("Real Total:" + realTotal);
        int succNumTess4j = 0;
        for (File f : files) {
            String name = f.getName();
            String real = name.substring(0, name.lastIndexOf("."));
            String result = recognizeText(f);
            result = screenLetterAndNum(result);

            if (real.equalsIgnoreCase(result)) {
                ++succNumTess4j;
            }
            if (result.length() != 6) {
                afterTotalTess4j--;
            }
            System.out.println("[Tess4j] Real: " + real + " Result: " + result);
        }
        succRateTess4j = succNumTess4j * 100.0 / realTotal;
        int addNumTess4j = (int) ((realTotal - afterTotalTess4j) * succRateTess4j / 100);
        afterSuccRateTess4j = (succNumTess4j + addNumTess4j) * 100.0 / realTotal;
        System.out.println("Tess4j Result Real Total:" + realTotal + ",Success:" + succNumTess4j);
        System.out.println("Tess4j Result After Total:" + afterTotalTess4j + ",Success:" + succNumTess4j);
        System.out.println("Tess4j Real正确率：" + succRateTess4j + "%");
        System.out.println("Tess4j After正确率：" + afterSuccRateTess4j + "%");
    }

    private final static String LANG_OPTION = "-l";  //英文字母小写l，并非数字1
    private final static String EOL = System.getProperty("line.separator");

    public static String recognizeText(File imageFile)throws Exception{
        File tempImage = imageFile;
        File outputFile = new File(imageFile.getParentFile(),"output");
        StringBuffer strB = new StringBuffer();
        List cmd = new ArrayList();
        cmd.add("tesseract");
        cmd.add("");
        cmd.add(outputFile.getName());
        cmd.add(LANG_OPTION);
        cmd.add("eng");
        //cmd.add("eng");

        ProcessBuilder pb = new ProcessBuilder();
        pb.directory(imageFile.getParentFile());

        cmd.set(1, tempImage.getName());
        pb.command(cmd);
        pb.redirectErrorStream(true);

        Process process = pb.start();
        //tesseract.exe 1.jpg 1 -l chi_sim
        int w = process.waitFor();

        //删除临时正在工作文件
//        tempImage.delete();

        if(w==0){
            BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(outputFile.getAbsolutePath()+".txt"),"UTF-8"));
            String str;
            while((str = in.readLine())!=null){
                strB.append(str).append(EOL);
            }
            in.close();
        }else{
            String msg;
            switch(w){
                case 1:
                    msg = "Errors accessing files.There may be spaces in your image's filename.";
                    break;
                case 29:
                    msg = "Cannot recongnize the image or its selected region.";
                    break;
                case 31:
                    msg = "Unsupported image format.";
                    break;
                default:
                    msg = "Errors occurred.";
            }
//            tempImage.delete();
//            throw new RuntimeException(msg);
        }
//        new File(outputFile.getAbsolutePath()+".txt").delete();
        return strB.toString();
    }

    public static String screenLetterAndNum(String str) {
        if (str == null) {
            return "";
        }
        char[] chars = str.toCharArray();
        StringBuilder strBf = new StringBuilder();
        strBf.setLength(0);
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if (CharUtil.isNum(c) || CharUtil.isLetter(c)) {
                strBf.append(c);
            }
        }
        return strBf.toString();
    }
}
